package com.cqeec.waimai_jsp.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/captcha")
public class CapthcaController extends HttpServlet {
    // 组成验证码的字符常量
    private static final String CHARACTERS = "0123456789";
    private static final int WIDTH = 200; //验证码图片的宽
    private static final int HEIGHT = 38; //验证码图片的高

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        char[] code = new char[4];
        // 生成验证码图片的响应设置
        // 设置页面缓存
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        // 网页缓存过期时间
        resp.setDateHeader("Expires", 0);
        // 设置响应内容类型
        resp.setContentType("image/jpeg");
        // 创建随机对象
        Random r = new Random();
        // 随机生成验证码
        for (int i = 0; i < 4; i++) {
            code[i] = CHARACTERS.charAt(r.nextInt(CHARACTERS.length()));
        }
        // 将验证码放入会话对象用于登录时进行验证
        req.getSession().setAttribute("code", String.valueOf(code));
        // 通过BufferedImage生成图片，并绘制背景
        BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_RGB);
        // 获取缓存图片的图形对象
        Graphics g = bi.getGraphics();
        // 填充矩形
        g.fillRect(0, 0, WIDTH, HEIGHT);
        // 干扰线
        for (int i = 1; i <= 10; i++) {
            // 设置画笔颜色
            g.setColor(new Color(r.nextInt(255), r.nextInt(255),
                    r.nextInt(255)));
            // 绘制线条
            g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT),
                    r.nextInt(WIDTH), r.nextInt(HEIGHT));
        }
        // 将生成验证码的每个字符以不同的颜色绘到图片上
        g.setFont(new Font("隶书", Font.BOLD, 36));
        for (int i = 0, x = 10; i < 4; i++, x += 50) {
            // 设置画笔颜色
            g.setColor(new Color(r.nextInt(255), r.nextInt(255),
                    r.nextInt(255)));
            // 在指定坐标处绘制字符
            g.drawString(code[i] + "", x, 30);
        }
        // 通过response对象将验证码图片发送到客户端浏览器
        ImageIO.write(bi, "jpg", resp.getOutputStream());
    }
}